const express = require('express')
const app = express()
const bcrypt = require('bcrypt')

var bodyParser = require('body-parser')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse application/json
app.use(bodyParser.json())

// 定义用户容器
const users = []

// 请求用户列表
app.get('/users', (req, res)=>{
  res.json(users)
})

// 添加用户
app.post('/users', async(req, res)=>{
  try {
    const salt = await bcrypt.genSalt(10)
    const hashedPassword = await bcrypt.hash(req.body.password, salt)
    const user = {name:req.body.name,password:hashedPassword}
    users.push(user)
    res.status(201).send(user)
  } catch (error) {
    res.status(500).send(error)
  }
})

// 用户登录
app.post('/users/login', async (req, res)=>{
  const user = users.find(user=> user.name = req.body.name )
  if(user == null) {
    return res.status(400).send('cannot find user')
  }
  try {
    const result = await bcrypt.compare(req.body.password, user.password)
    if(result) {
      res.send('success')
    }else {
      res.status(400).send('failed')
    }
  } catch (error) {
    res.status(500).send(error)
  }
})


app.listen(3000)